package com.ruiyun.app.lib.logcat;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.Nullable;


/**
 * Created by root on 15-11-9.
 */
public class MyView extends androidx.appcompat.widget.AppCompatImageView {

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private static int timeout=400;//双击间四百毫秒延时
    private int clickCount = 0;//记录连续点击次数
    private Handler handler;
    private MyClickCallBack myClickCallBack;
    public interface MyClickCallBack{
        void oneClick();//点击一次的回调
        void doubleClick();//连续点击两次的回调

    }

    public void setMyClickCallBack(MyClickCallBack myClickCallBack) {
        this.myClickCallBack = myClickCallBack;
        handler = new Handler();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(handler!=null && myClickCallBack!=null){
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                clickCount++;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (clickCount == 1) {
                            myClickCallBack.oneClick();
                        }else if(clickCount==2){
                            myClickCallBack.doubleClick();
                        }
                        handler.removeCallbacksAndMessages(null);
                        //清空handler延时，并防内存泄漏
                        clickCount = 0;//计数清零
                    }
                },timeout);//延时timeout后执行run方法中的代码
            }
        }
        return false;//让点击事件继续传播，方便再给View添加其他事件监听
    }
}